<template>
  <div class="search-bar">
    <div class="search-input-wrapper">
      <span class="search-icon">🔍</span>
      <input
        v-model="searchValue"
        type="text"
        :placeholder="placeholder"
        class="search-input"
        @input="handleInput"
        @keyup.enter="handleSearch"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索商品',
  },
  modelValue: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue', 'search', 'input'])

const searchValue = ref(props.modelValue)

// 监听外部值变化
watch(
  () => props.modelValue,
  newValue => {
    searchValue.value = newValue
  }
)

// 监听内部值变化，同步到外部
watch(searchValue, newValue => {
  emit('update:modelValue', newValue)
})

// 处理输入
const handleInput = event => {
  emit('input', event)
}

// 处理搜索
const handleSearch = () => {
  emit('search', searchValue.value)
}
</script>

<style scoped lang="less">
@import (reference) '../../styles/global.less';

.search-bar {
  padding: 15px;
  background-color: @white;
  position: sticky;
  top: 0;
  z-index: 100;
  box-shadow: @box-shadow;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f0f0f0;
  border-radius: 20px;
  padding: 8px 15px;

  .search-icon {
    margin-right: 8px;
    color: @text-color-tertiary;
  }

  .search-input {
    flex: 1;
    border: none;
    background: transparent;
    outline: none;
    font-size: @font-size-sm;
  }
}
</style>
